package com.bizdk.generator.core;

import com.bizdk.generator.core.query.ClickHouseQuery;
import com.bizdk.generator.core.query.DialectQuery;
import com.bizdk.generator.core.query.DmQuery;
import com.bizdk.generator.core.query.MySqlQuery;
import com.bizdk.generator.core.query.OracleQuery;
import com.bizdk.generator.core.query.PostgreSqlQuery;
import com.bizdk.generator.core.query.SQLServerQuery;
import com.bizdk.generator.entity.gen.Datasrc;
import lombok.Data;
import lombok.extern.slf4j.Slf4j;

import java.sql.Connection;
import java.sql.SQLException;

/**
 * 代码生成器 数据源
 */
@Data
@Slf4j
public class GenDataSrc {
    
    /**
     * 数据源ID
     */
    private Long id;
    
    /**
     * 数据库类型
     */
    private DbType dbType;
    
    /**
     * 数据库URL
     */
    private String connUrl;
    
    /**
     * 用户名
     */
    private String username;
    
    /**
     * 密码
     */
    private String password;
    
    private DialectQuery dbQuery;
    
    private Connection connection;
    
    public GenDataSrc(Datasrc entity) {
        this.id = entity.getId();
        this.dbType = DbType.getValue(entity.getDbType());
        this.connUrl = entity.getConnUrl();
        this.username = entity.getUsername();
        this.password = entity.getPassword();
        
        if (dbType == DbType.MySQL) {
            this.dbQuery = new MySqlQuery();
        } else if (dbType == DbType.Oracle) {
            this.dbQuery = new OracleQuery();
        } else if (dbType == DbType.PostgreSQL) {
            this.dbQuery = new PostgreSqlQuery();
        } else if (dbType == DbType.SQLServer) {
            this.dbQuery = new SQLServerQuery();
        } else if (dbType == DbType.DM) {
            this.dbQuery = new DmQuery();
        } else if (dbType == DbType.Clickhouse) {
            this.dbQuery = new ClickHouseQuery();
        }
        
        try {
            this.connection = DbUtils.getConnection(this);
        } catch (Exception e) {
            log.error(e.getMessage(), e);
        }
    }
    
    public GenDataSrc(Connection connection) throws SQLException {
        this.id = 0L;
        this.dbType = DbType.getValue(connection.getMetaData().getDatabaseProductName());
        
        if (dbType == DbType.MySQL) {
            this.dbQuery = new MySqlQuery();
        } else if (dbType == DbType.Oracle) {
            this.dbQuery = new OracleQuery();
        } else if (dbType == DbType.PostgreSQL) {
            this.dbQuery = new PostgreSqlQuery();
        } else if (dbType == DbType.SQLServer) {
            this.dbQuery = new SQLServerQuery();
        } else if (dbType == DbType.DM) {
            this.dbQuery = new DmQuery();
        } else if (dbType == DbType.Clickhouse) {
            this.dbQuery = new ClickHouseQuery();
        }
        
        this.connection = connection;
    }
}
